import sqlite3

print("=== 检查n8n用户记忆状态 ===")

# 连接到数据库
conn = sqlite3.connect('./openmemory.db')
cursor = conn.cursor()

# 1. 检查所有用户
cursor.execute("SELECT id, name FROM users")
users = cursor.fetchall()
print(f"\n1. 发现 {len(users)} 个用户:")
for user in users:
    print(f"   - ID: {user[0]}, 名称: {user[1]}")

# 2. 检查default_user是否存在
cursor.execute("SELECT id FROM users WHERE name = 'default_user'")
default_user = cursor.fetchone()
print(f"\n2. default_user: {default_user}")

if default_user:
    user_id = default_user[0]
    
    # 3. 检查该用户的所有记忆
    cursor.execute("""
        SELECT a.name, COUNT(m.id) as memory_count
        FROM apps a
        JOIN memories m ON a.id = m.app_id
        WHERE m.user_id = ?
        GROUP BY a.id, a.name
    """, (user_id,))
    
    memories = cursor.fetchall()
    print(f"\n3. default_user的记忆分布:")
    for app_name, count in memories:
        print(f"   - {app_name}: {count} 条记忆")
    
    # 4. 检查具体的记忆内容
    cursor.execute("""
        SELECT m.id, m.content, a.name as app_name, m.created_at
        FROM memories m
        JOIN apps a ON m.app_id = a.id
        WHERE m.user_id = ?
        ORDER BY m.created_at DESC
        LIMIT 5
    """, (user_id,))
    
    latest_memories = cursor.fetchall()
    print(f"\n4. default_user最新的5条记忆:")
    for memory in latest_memories:
        content_preview = memory[1][:50] + "..." if len(memory[1]) > 50 else memory[1]
        print(f"   - {memory[2]}: {content_preview}")

else:
    print("\n3. default_user不存在，检查其他用户...")
    # 检查所有用户的记忆
    cursor.execute("""
        SELECT u.name, a.name, COUNT(m.id) as memory_count
        FROM users u
        JOIN memories m ON u.id = m.user_id
        JOIN apps a ON m.app_id = a.id
        GROUP BY u.id, u.name, a.id, a.name
        ORDER BY u.name, memory_count DESC
    """)
    
    all_user_memories = cursor.fetchall()
    print("\n所有用户的记忆分布:")
    for user_name, app_name, count in all_user_memories:
        print(f"   - {user_name} -> {app_name}: {count} 条记忆")

# 5. 检查是否有未关联用户的记忆
cursor.execute("""
    SELECT a.name, COUNT(m.id) as memory_count
    FROM apps a
    JOIN memories m ON a.id = m.app_id
    WHERE m.user_id IS NULL OR m.user_id = ''
    GROUP BY a.id, a.name
""")

orphan_memories = cursor.fetchall()
if orphan_memories:
    print(f"\n5. 未关联用户的记忆:")
    for app_name, count in orphan_memories:
        print(f"   - {app_name}: {count} 条记忆")

conn.close()

print("\n=== 检查完成 ===")